#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
Introduction to Programming in Java - An Interdisciplinary Approach

All book programs ported to Python by
Scott C. King (revisionx at {gee}ma1l <dot> c0m).

All program examples pass Pylint with a perfect 10.00 score.
Pylint:  http://www.pylint.org/


# Program 1.3.7 - Converting to binary

Syntax:
python binary.py 19


Notes:
int(sys.argv[1]) == Integer.parseInt(args[0])

sys is a required import here in order to use command line arguments.
https://docs.python.org/2/tutorial/stdlib.html

Why sys.stdout.write?  Python's in-line print w/comma inserts a space between
items.  You could built a list and join the elements using join, but I want
the Python to remain on par with the Java at this stage in the book.

'''

import sys


def main():
    ''' Print binary representation of positive integer '''

    number = int(sys.argv[1])
    cur_pow = 1
    while cur_pow <= number/2:
        cur_pow = 2*cur_pow
    # cur_pow is the largest power of 2 <= number

    excess = number
    while cur_pow > 0:
        # Cast out powers of two in decreasing order
        if excess < cur_pow:
            sys.stdout.write('0')
        else:
            sys.stdout.write('1')
            excess -= cur_pow
        cur_pow = cur_pow/2
    print


if __name__ == '__main__':
    main()
